import 'dart:async';

import 'package:huxiaodui/api/api.dart';
import 'package:huxiaodui/api/model/result.dart';
import 'package:huxiaodui/api/model/mobile_app_model.dart';
import 'package:huxiaodui/components/code_input.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:huxiaodui/utils/global_controller.dart';
import 'package:provider/provider.dart';

class MyInfoPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyInfoPageState();
}

class MyInfoPageState extends State<MyInfoPage> {
  var nameController = TextEditingController();
  var accountController = TextEditingController();
  var sexController = TextEditingController();
  var telController = TextEditingController();
  var jobController = TextEditingController();
  var addrController = TextEditingController();
  var emailController = TextEditingController();

  Future<void> accountDelete() async {
    var passController = TextEditingController();
    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('是否确认注销账号？'),
        content: const Text("注销之后无法找回！"),
        actions: [
          TextButton(
            child: const Text('取消'),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
          TextButton(
            child: const Text('确定'),
            onPressed: () async {
              Navigator.pop(context);
              await showDialog(
                context: context,
                builder: (context) => AlertDialog(
                  title: const Text('请再次确定并输入密码'),
                  content: TextField(
                    textInputAction: TextInputAction.next,
                    keyboardType: TextInputType.visiblePassword,
                    obscureText: true,
                    controller: passController,
                    decoration: const InputDecoration(
                      prefixIcon: Icon(Icons.password),
                      hintText: "请输入密码",
                      labelText: "密码",
                    ),
                  ),
                  actions: [
                    TextButton(
                      child: const Text('取消'),
                      onPressed: () {
                        Navigator.pop(context, false);
                      },
                    ),
                    TextButton(
                      child: const Text('确定'),
                      onPressed: () async {
                        await Api.mobileApp
                            .delete(accountController.text, passController.text)
                            .then(
                          (value) {
                            Navigator.pop(context, true);
                            passController.text = "";
                          },
                        );
                      },
                    ),
                  ],
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Future<void> passwordEdit() async {
    var passController = TextEditingController();

    var newPassController = TextEditingController();
    var newRePassController = TextEditingController();
    await showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('修改密码'),
        content: SizedBox(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.visiblePassword,
                obscureText: true,
                controller: passController,
                decoration: const InputDecoration(
                  prefixIcon: Icon(Icons.password),
                  hintText: "请输入原密码",
                  labelText: "原密码密码",
                ),
              ),
              TextField(
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.visiblePassword,
                obscureText: true,
                controller: newPassController,
                decoration: const InputDecoration(
                  prefixIcon: Icon(Icons.password),
                  hintText: "请输入新密码",
                  labelText: "新密码",
                ),
              ),
              TextField(
                textInputAction: TextInputAction.next,
                keyboardType: TextInputType.visiblePassword,
                obscureText: true,
                controller: newRePassController,
                decoration: const InputDecoration(
                  prefixIcon: Icon(Icons.password),
                  hintText: "请再次输入新密码",
                  labelText: "新密码",
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            child: const Text('取消'),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
          TextButton(
            child: const Text('确定'),
            onPressed: () async {
              if (passController.text.isEmpty) {
                EasyLoading.showError("请输入原密码");
                return;
              }
              if (newPassController.text.isEmpty) {
                EasyLoading.showError("请输入新密码");
                return;
              }
              if (newRePassController.text.isEmpty) {
                EasyLoading.showError("请再次输入原密码");
                return;
              }

              if (newRePassController.text != newPassController.text) {
                EasyLoading.showError("两次密码不一致");
                return;
              }
              Api.mobileApp.updatePassword(passController.text, newPassController.text).then((value){
                Navigator.pop(context);
              });

            },
          ),
        ],
      ),
    );
  }

  Future<void> forget() async {
    var codeController = TextEditingController();
    var newPassController = TextEditingController();
    var newRePassController = TextEditingController();

    if (emailController.text.isEmpty) {
      EasyLoading.showError("请先绑定邮箱或手机号");
      return;
    }
    await showDialog(
      barrierDismissible: false,
      context: context,
      builder: (context) {
        Future<bool> getCode() async {
          bool aaa = false;

          await Api.request(
            isToast: true,
            data: {"email": emailController.text},
            url: MobileAppUrl.forgetByEmailCode,
            success: (res) {
              aaa = true;
            },
          );
          return aaa;
        }

        return AlertDialog(
          title: const Text('找回密码'),
          content: SizedBox(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  textInputAction: TextInputAction.next,
                  readOnly: true,
                  controller: emailController,
                  decoration: const InputDecoration(
                    prefixIcon: Icon(Icons.email),
                    hintText: "请输入邮箱地址",
                    labelText: "邮箱",
                  ),
                ),
                CodeInput(
                  codeController: codeController,
                  getCode: () async => await getCode(),
                ),
                TextField(
                  textInputAction: TextInputAction.next,
                  keyboardType: TextInputType.visiblePassword,
                  obscureText: true,
                  controller: newPassController,
                  decoration: const InputDecoration(
                    prefixIcon: Icon(Icons.password),
                    hintText: "请输入新密码",
                    labelText: "新密码",
                  ),
                ),
                TextField(
                  textInputAction: TextInputAction.next,
                  keyboardType: TextInputType.visiblePassword,
                  obscureText: true,
                  controller: newRePassController,
                  decoration: const InputDecoration(
                    prefixIcon: Icon(Icons.password),
                    hintText: "请再次输入新密码",
                    labelText: "新密码",
                  ),
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              child: const Text('取消'),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            TextButton(
              child: const Text('确定'),
              onPressed: () async {
                Api.request(
                  isToast: true,
                  url: MobileAppUrl.forgetByEmail,
                  data: {
                    "email": emailController.text,
                    "code": codeController.text,
                    "password": newPassController.text,
                  },
                  success: (res) {
                    Navigator.pop(context);
                  },
                );
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> bindEmail() async {
    var codeController = TextEditingController();

    emailController.text.isEmpty
        ? await showDialog(
            barrierDismissible: false,
            context: context,
            builder: (context) {
              var ec = TextEditingController();

              return AlertDialog(
                title: const Text('邮箱绑定'),
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    TextField(
                      textInputAction: TextInputAction.next,
                      controller: ec,
                      decoration: const InputDecoration(
                        prefixIcon: Icon(Icons.email),
                        hintText: "请输入邮箱地址",
                        labelText: "邮箱",
                      ),
                    ),
                    CodeInput(
                      codeController: codeController,
                      getCode: () async {
                        bool aaa = false;
                        if (ec.text.isEmpty) {
                          EasyLoading.showError("请输入邮箱");
                          return false;
                        }
                        await Api.mobileApp.bindEmailCode(ec.text).then((value){
                          aaa = true;
                        });

                        return aaa;
                      },
                    ),
                  ],
                ),
                actions: [
                  TextButton(
                    child: const Text('取消'),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                  TextButton(
                    child: const Text('绑定'),
                    onPressed: () async {
                      Api.mobileApp.bindEmail(ec.text, codeController.text).then((_) {
                        emailController.text = ec.text;
                        Navigator.pop(context);
                      });
                    },
                  ),
                ],
              );
            },
          )
        : await showDialog(
            barrierDismissible: false,
            context: context,
            builder: (context) {
              return AlertDialog(
                title: const Text('邮箱解绑'),
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    TextField(
                      textInputAction: TextInputAction.next,
                      controller: emailController,
                      decoration: const InputDecoration(
                        prefixIcon: Icon(Icons.email),
                        hintText: "请输入邮箱地址",
                        labelText: "邮箱",
                      ),
                    ),
                    CodeInput(
                      codeController: codeController,
                      getCode: () async {
                        bool ok = false;
                        Api.mobileApp.unbindEmailCode(emailController.text).then((_) {
                          ok = true;
                        });
                        return ok;
                      },
                    ),
                  ],
                ),
                actions: [
                  TextButton(
                    child: const Text('取消'),
                    onPressed: () {
                      Navigator.pop(context);
                    },
                  ),
                  TextButton(
                    child: const Text('解绑'),
                    onPressed: () async {
                      Api.request(
                        isToast: true,
                        url: MobileAppUrl.unbindEmail,
                        data: {
                          "email": emailController.text,
                          "code": codeController.text,
                        },
                        success: (res) {
                          GlobalController().user?.email = "";
                          emailController.text = "";
                          GlobalController().refresh();
                          Navigator.pop(context);
                        },
                      );
                    },
                  ),
                ],
              );
            },
          );
  }

  @override
  Widget build(BuildContext context) {
    var user = Provider.of<GlobalController>(context).user;
    nameController.text = user!.name;
    accountController.text = user.account;
    sexController.text = user.sex;
    telController.text = user.tel;
    jobController.text = MobileAppModel.jobList[user.job];
    addrController.text = user.addr;
    int job = user.job;
    emailController.text = user.email;

    return Scaffold(
      appBar: AppBar(
        title: const Text("用户信息"),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              textInputAction: TextInputAction.next,
              readOnly: true,
              controller: accountController,
              keyboardType: TextInputType.phone,
              decoration: const InputDecoration(
                prefixIcon: Icon(Icons.people),
                hintText: "请输入账号",
                labelText: "账号",
              ),
            ),
            const SizedBox(height: 10),
            TextField(
              textInputAction: TextInputAction.next,
              controller: nameController,
              keyboardType: TextInputType.name,
              decoration: const InputDecoration(
                prefixIcon: Icon(Icons.account_box),
                hintText: "请输入名字",
                labelText: "名字",
              ),
            ),
            const SizedBox(height: 10),
            TextField(
              textInputAction: TextInputAction.none,
              readOnly: true,
              controller: sexController,
              onTap: () {
                showModalBottomSheet(
                  context: context,
                  builder: (context) => Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      ListTile(
                        title: const Center(
                          child: Text('男'), // 将文本居中显示
                        ),
                        onTap: () async {
                          sexController.text = "男";
                          Navigator.pop(context);
                        },
                      ),
                      ListTile(
                        title: const Center(
                          child: Text('女'), // 将文本居中显示
                        ),
                        onTap: () async {
                          sexController.text = "女";
                          Navigator.pop(context);
                        },
                      ),
                      ListTile(
                        title: const Center(
                          child: Text('隐藏'), // 将文本居中显示
                        ),
                        onTap: () async {
                          sexController.text = "隐藏";
                          Navigator.pop(context);
                        },
                      ),
                    ],
                  ),
                );
              },
              keyboardType: TextInputType.text,
              decoration: const InputDecoration(
                prefixIcon: Icon(Icons.man),
                hintText: "请选择性别",
                labelText: "性别",
              ),
            ),
            const SizedBox(height: 10),
            TextField(
              textInputAction: TextInputAction.next,
              controller: telController,
              keyboardType: TextInputType.phone,
              decoration: const InputDecoration(
                prefixIcon: Icon(Icons.phone),
                hintText: "请输入联系方式",
                labelText: "联系方式",
              ),
            ),
            const SizedBox(height: 10),
            TextField(
              textInputAction: TextInputAction.none,
              readOnly: true,
              controller: jobController,
              onTap: () {
                Pickers.showSinglePicker(
                  context,
                  data: MobileAppModel.jobList,
                  onConfirm: (data, index) {
                    jobController.text = MobileAppModel.jobList[index];
                    job = index;
                  },
                );
              },
              keyboardType: TextInputType.text,
              decoration: const InputDecoration(
                prefixIcon: Icon(Icons.perm_identity),
                hintText: "请选择身份",
                labelText: "身份",
              ),
            ),
            const SizedBox(height: 10),
            TextField(
              textInputAction: TextInputAction.next,
              controller: addrController,
              keyboardType: TextInputType.streetAddress,
              decoration: const InputDecoration(
                prefixIcon: Icon(Icons.location_city),
                hintText: "请输入所在地",
                labelText: "所在地",
              ),
            ),
            const SizedBox(height: 10),
            TextField(
              textInputAction: TextInputAction.next,
              readOnly: true,
              controller: emailController,
              keyboardType: TextInputType.emailAddress,
              decoration: const InputDecoration(
                prefixIcon: Icon(Icons.email_outlined),
                hintText: "请绑定邮箱地址",
                labelText: "邮箱地址",
              ),
              onTap: () {
                bindEmail();
              },
            ),
            const SizedBox(height: 30),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () => accountDelete(),
                  style: ButtonStyle(
                      backgroundColor:
                          MaterialStateProperty.all<Color?>(Colors.redAccent)),
                  child: const SizedBox(
                      width: 90,
                      child: Row(
                        children: [
                          Icon(Icons.remove_circle),
                          SizedBox(width: 5),
                          Text("注销账号"),
                        ],
                      )),
                ),
                ElevatedButton(
                  onPressed: () {
                    Api.mobileApp
                        .update(
                            name: nameController.text,
                            sex: sexController.text,
                            tel: telController.text,
                            job: job,
                            addr: addrController.text)
                        .then((value) {
                      Navigator.pop(context);
                    });
                  },
                  child: const SizedBox(
                      width: 90,
                      child: Row(
                        children: [
                          Icon(Icons.save),
                          SizedBox(width: 5),
                          Text("保存修改"),
                        ],
                      )),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                ElevatedButton(
                  onPressed: () async => await passwordEdit(),
                  style: ButtonStyle(
                      backgroundColor:
                          MaterialStateProperty.all<Color?>(Colors.lightBlue)),
                  child: const SizedBox(
                    width: 90,
                    child: Row(
                      children: [
                        Icon(Icons.edit_calendar),
                        SizedBox(width: 5),
                        Text("修改密码"),
                      ],
                    ),
                  ),
                ),
                ElevatedButton(
                  onPressed: () async => await forget(),
                  style: ButtonStyle(
                      backgroundColor:
                          MaterialStateProperty.all<Color?>(Colors.blueAccent)),
                  child: const SizedBox(
                    width: 90,
                    child: Row(
                      children: [
                        Icon(Icons.question_mark),
                        SizedBox(width: 5),
                        Text("忘记密码"),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
